package web.Roles;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import entity.RolesBean;
import services.RolesServiceAll;
import services.Roles_PerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/addRolesAndPermi")
public class AddRolesAndPermi extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        RolesServiceAll rolesServiceAll = new RolesServiceAll();
        String Rname = req.getParameter("Rname");
        String Rdescribe = req.getParameter("Rdescribe");
        RolesBean rolesBean = new RolesBean();
        int rId = rolesServiceAll.all().size();
        rolesBean.setRid(rId);
        rolesBean.setRname(Rname);
        rolesBean.setRdescribe(Rdescribe);
        if("".equals(Rdescribe)){
            System.out.println("描述内容为空");
        }
        rolesServiceAll.add(rolesBean);

        // 以下是添加该角色的权限
        String checkedNodesStr = req.getParameter("checkedNodes");
        Roles_PerService roles_perService = new Roles_PerService();
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String,Object>> list = mapper.readValue(checkedNodesStr,new TypeReference<List<Map<String,Object>>>(){});
        for(Map<String,Object> obj:list){
            if(obj.get("Plevel").toString().equals("0")){
                roles_perService.add(rolesBean.getRid(),Integer.parseInt(obj.get("Pid").toString()));
            }
        }

        // 以下是响应回去的
        Gson gson = new Gson();
        String json = gson.toJson("添加角色成功");
        resp.getWriter().println(json);
    }
}
